using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

namespace F1RacingGame
{
    public class GameEngine
    {
        private Timer gameTimer;
        private Form gameForm;
        private Graphics graphics;
        private BufferedGraphics bufferedGraphics;
        private BufferedGraphicsContext context;
        private GameState currentState;
        private Dictionary<GameState, IGameScreen> screens;
        
        // 游戏常量 - 调整为竖版布局
        public const int GAME_WIDTH = 640;  // 适合竖版布局
        public const int GAME_HEIGHT = 800; // 竖版高度
        public const int FPS = 60;
        
        // 帧率控制
        private DateTime lastFrameTime;
        private const int TARGET_FRAME_TIME = 1000 / FPS; // 毫秒
        private int frameCount = 0;
        private DateTime fpsStartTime;
        
        public GameEngine(Form form)
        {
            gameForm = form;
            graphics = form.CreateGraphics();
            screens = new Dictionary<GameState, IGameScreen>();
            
            // 初始化双缓冲
            InitializeDoubleBuffering();
            
            InitializeGame();
        }
        
        private void InitializeDoubleBuffering()
        {
            // 创建双缓冲上下文 - 使用更大的缓冲区避免溢出
            context = BufferedGraphicsManager.Current;
            context.MaximumBuffer = new Size(GAME_WIDTH + 2, GAME_HEIGHT + 2);
            
            // 重新分配缓冲区以确保稳定性
            if (bufferedGraphics != null)
            {
                bufferedGraphics.Dispose();
            }
            bufferedGraphics = context.Allocate(graphics, new Rectangle(0, 0, GAME_WIDTH, GAME_HEIGHT));
            
            // 设置缓冲区质量
            bufferedGraphics.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
            bufferedGraphics.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
            bufferedGraphics.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
            bufferedGraphics.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
        }
        
        private void InitializeGame()
        {
            // 设置窗体属性
            gameForm.Size = new Size(GAME_WIDTH, GAME_HEIGHT);
            gameForm.Text = "F1 Racing Game";
            gameForm.FormBorderStyle = FormBorderStyle.FixedSingle;
            gameForm.MaximizeBox = false;
            gameForm.StartPosition = FormStartPosition.CenterScreen;
            
            // 初始化帧率控制
            lastFrameTime = DateTime.Now;
            fpsStartTime = DateTime.Now;
            frameCount = 0;
            
            // 初始化游戏屏幕
            screens[GameState.MainMenu] = new MainMenuScreen();
            screens[GameState.GamePlay] = new GamePlayScreen();
            screens[GameState.Settings] = new SettingsScreen();
            screens[GameState.Demo] = new DemoScreen();
            screens[GameState.Leaderboard] = new LeaderboardScreen();
            
            // 设置初始状态
            currentState = GameState.MainMenu;
            
            // 初始化游戏定时器
            gameTimer = new Timer();
            gameTimer.Interval = 1000 / FPS;
            gameTimer.Tick += GameLoop;
            gameTimer.Start();
            
            // 设置键盘事件
            gameForm.KeyDown += OnKeyDown;
            gameForm.KeyUp += OnKeyUp;
        }
        
        private void GameLoop(object sender, EventArgs e)
        {
            // 帧率控制
            DateTime currentTime = DateTime.Now;
            int elapsedMs = (int)(currentTime - lastFrameTime).TotalMilliseconds;
            
            // 更精确的帧率控制
            if (elapsedMs < TARGET_FRAME_TIME - 1) // 留1ms余量
            {
                return; // 跳过这一帧以维持目标帧率
            }
            
            lastFrameTime = currentTime;
            frameCount++;
            
            // 每60帧重新初始化缓冲区（防止内存泄漏）
            if (frameCount % 60 == 0)
            {
                InitializeDoubleBuffering();
            }
            
            // 更新当前屏幕
            if (screens.ContainsKey(currentState))
            {
                screens[currentState].Update();
                
                try
                {
                    // 清除缓冲区
                    bufferedGraphics.Graphics.Clear(Color.Black);
                    
                    // 渲染到缓冲区
                    screens[currentState].Render(bufferedGraphics.Graphics);
                    
                    // 将缓冲区内容复制到屏幕
                    bufferedGraphics.Render(graphics);
                }
                catch (Exception ex)
                {
                    // 如果渲染出错，重新初始化双缓冲
                    System.Diagnostics.Debug.WriteLine($"Render error: {ex.Message}");
                    InitializeDoubleBuffering();
                }
            }
        }
        
        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (screens.ContainsKey(currentState))
            {
                screens[currentState].OnKeyDown(e);
            }
        }
        
        private void OnKeyUp(object sender, KeyEventArgs e)
        {
            if (screens.ContainsKey(currentState))
            {
                screens[currentState].OnKeyUp(e);
            }
        }
        
        public void ChangeState(GameState newState)
        {
            if (screens.ContainsKey(newState))
            {
                currentState = newState;
                screens[currentState].Initialize();
            }
        }
        
        public GameState GetCurrentState()
        {
            return currentState;
        }
        
        public void Dispose()
        {
            gameTimer?.Stop();
            gameTimer?.Dispose();
            graphics?.Dispose();
            bufferedGraphics?.Dispose();
        }
    }
    
    public enum GameState
    {
        MainMenu,
        GamePlay,
        Settings,
        Demo,
        Leaderboard
    }
} 